<template>
	<view>
		<uni-transition :duration="300" :mode-class="['fade']" :styles="maskClass" @click="togglePopup" :show="currentIsPopupShow">
		</uni-transition>
		<uni-transition :duration="260" :mode-class="['slide-bottom']" :styles="popupTransfromClass" :show="currentIsPopupShow">
			<view class="picker-wrapper">
				<view class="btn-wrapper">
					<view class="btn"  @click="togglePopup">取消</view>
					<view class="btn" @click="pickerConfirm">确定</view>
				</view>
				<picker-view :value="value" @change="regionChange" @pickstart="chooseStart" @pickend="chooseEnd" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="item in provinces" :key="item.id">{{item.name}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="item in citys" :key="item.id">{{item.name}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="item in areas" :key="item.id">{{item.name}}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</uni-transition>
	</view>
</template>

<script>
import uniTransition from '@/components/uni-transition/uni-transition.vue'
import { getAllProvinces, getByParentIds} from '@/api/address.js'
export default {
	components: {uniTransition},
  props: {
	  initFlag: {
		  type: Boolean,
		  default: true
	  },
	  isPopupShow: {
		  type: Boolean,
		  default: false
	  },
	  selectProvinceId: {
		type: String,
		default: ''
	  },
	  selectCityId: {
		type: String,
		default: ''
	  },
	  selectAreaId: {
		type: String,
		default: ''
	  },
	  region: {
		  type: String,
		  default: ''
	  }
  },
  data() {
    return {
      maskClass: {
      	'position': 'fixed',
      	'bottom': 0,
      	'top': 0,
      	'left': 0,
      	'right': 0,
      	'z-index': 10,
      	'background-color': 'rgba(0, 0, 0, 0.6)'
      },
      popupTransfromClass: {
      	'position': 'fixed',
      	'bottom': 0,
      	'left': 0,
      	'right': 0,
      	'z-index': 11,
      	'background-color': '#fff'
      },
      areaId: '',
      cityId: '',
      provinceId: '',
      value: [0, 0, 0], // 地址选择器省市区 暂存 currentIndex
      regionValue: [0, 0, 0], // 地址选择器省市区 最终 currentIndex
      provinces: [], // 一级地址
      citys: [], // 二级地址
      areas: [], // 三级地址
      isCanConfirm: true //是否禁止在第一列滚动期间点击确定提交数据
    }
  },
  computed: {
    currentInitFlag: {
      get() {
        return this.initFlag
      },
      set(val) {
        this.$emit('update:initFlag', val)
      }
    },
	currentIsPopupShow: {
	  get() {
	    return this.isPopupShow
	  },
	  set(val) {
	    this.$emit('update:isPopupShow', val)
	  }
	},
	currentSelectProvinceId: {
	  get() {
	    return this.selectProvinceId
	  },
	  set(val) {
	    this.$emit('update:selectProvinceId', val)
	  }
	},
	currentSelectCityId: {
	  get() {
	    return this.selectCityId
	  },
	  set(val) {
	    this.$emit('update:selectCityId', val)
	  }
	},
	currentSelectAreaId: {
	  get() {
	    return this.selectAreaId
	  },
	  set(val) {
	    this.$emit('update:selectAreaId', val)
	  }
	},
	currentRegion: {
	  get() {
	    return this.region
	  },
	  set(val) {
	    this.$emit('update:region', val)
	  }
	}
  },
  created() {
	 
  },
  mounted() {
	   this.init()
  },
  methods: {
	  async init() {
		  if (this.selectProvinceId && this.selectAreaId && this.selectCityId) {
			  await this.getProvince()
			  this.provinceId = this.selectProvinceId
			  await this.getCity()
			  this.cityId = this.selectCityId 
			  await this.getArea()
			  this.areaId = this.selectAreaId
			  let val0 = this.provinces.map(e => e.id).indexOf(Number(this.selectProvinceId))
			  let val1 = this.citys.map(e => e.id).indexOf(Number(this.selectCityId))
			  let val2 = this.areas.map(e => e.id).indexOf(Number(this.selectAreaId))
			  this.value[0] = val0 !=-1 ? val0 : 0
			  this.value[1] = val1 !=-1 ? val1 : 0
			  this.value[2] = val2 !=-1 ? val2 : 0
			  this.currentInitFlag = false
		  } else {
			  this.currentInitFlag = false
			  await this.getProvince()
			  await this.getCity()
			  this.getArea()
		  }
	  },
    // 获取省
    getProvince () {
    	return new Promise(resolve => {
    	  getAllProvinces().then(respanse => {
    		this.provinces = respanse.result
    		this.provinceId = respanse.result[this.value[0]].id
    		resolve()
    	  })
    	})
    },
    
    // 获取市
    getCity () {
      if (!this.provinceId) {
    	return
      }
      const data = {
    	parendId: this.provinceId
      }
      return new Promise(resolve => {
    	getByParentIds(data).then(respanse => {
    	  this.citys = respanse.result
    	  this.cityId = respanse.result[this.value[1]].id
    	  resolve()
    	})
      })
    },
    
    // 获取区县
    getArea () {
      if (!this.cityId) {
    	return
      }
      const data = {
    	parendId: this.cityId
      }
      return new Promise(resolve => {
    	getByParentIds(data).then(respanse => {
    	  this.areas = respanse.result
    	  this.areaId = respanse.result[this.value[2]].id
    	  resolve()
    	})
      })
    },
    
    // 处理省市县联动逻辑 并保存 value
    async regionChange(e) {
    	console.log(e.detail.value)
    	var value = e.detail.value
    	var provinceNum = value[0]
    	var cityNum = value[1]
    	var areaNum = value[2]
    	if (this.value[0] !== provinceNum) {
    	  this.provinceId = this.provinces[provinceNum].id
    	  this.value = [provinceNum, 0, 0]
    	  await this.getCity()
    	  this.getArea()
    	} else if (this.value[1] !== cityNum) {
    	  this.cityId = this.citys[cityNum].id
    	  this.value = [provinceNum, cityNum, 0]
    	  this.getArea()
    	} else {
    		this.areaId = this.areas[areaNum].id
    	  this.value = [provinceNum, cityNum, areaNum]
    	}
    },
    		  
    chooseStart(e) {
      this.isCanConfirm = false
    },
    
    chooseEnd(e) {
      this.isCanConfirm = true
    },
    
    // 点击地区选择确定按钮
    pickerConfirm(e) {
        if (this.isCanConfirm) {
          var value = this.value
           this.currentIsPopupShow = false
          // 将选择的城市信息显示到输入框
          try {
            var region = (this.provinces[value[0]].name || '') +'/'+ (this.citys[value[1]].name || '')
    		this.currentSelectProvinceId = this.provinces[value[0]].id || ''
    		this.currentSelectCityId = this.citys[value[1]].id || ''
            if (this.areas.length > 0) {
              region = region +'/'+ this.areas[value[2]].name || ''
    		  this.currentSelectAreaId = this.areas[value[2]].id || ''
            } else {
    			this.currentSelectAreaId = this.areas[0].id
              this.value[2] = 0
            }
          } catch (error) {
            console.log('adress select something error')
          }
          this.currentRegion = region
          this.regionValue = [...this.value]
        }
    },
    
    togglePopup() {
    	this.currentIsPopupShow = !this.currentIsPopupShow
    }
  }
}
</script>

<style lang='scss' scoped>
  .picker-wrapper{
  	.item{
  		text-align: center;
  		line-height: 34px;
  		font-size: 28rpx;
  	}
  }
  .btn-wrapper{
  	display: flex;
  	justify-content: space-between;
  	padding-top: 10rpx;
  	.btn{
  		padding: 0 30rpx;
  		line-height: 60rpx;
  		font-size: 28rpx;
  		color: #007aff;
  	}
  }
  .picker-view{
  	height: 400rpx;
  }
</style>
